package com.hdoit.ares.selfcommon.jpush;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;

import com.hdoit.ares.logical.app.model.AppRemindMessage;
import com.hdoit.ares.logical.app.service.IAppRemindMessageService;
import com.hdoit.ares.logical.cust.model.Customer;
import com.hdoit.ares.selfcommon.enums.cust.CustomerLevel;
import com.tennetcn.common.enums.BaseEnumConstant;
import com.tennetcn.common.enums.ModelStatus;
import com.tennetcn.common.utils.CommonUtils;
import com.tennetcn.common.utils.DateUtils;
import common.Logger;


public class JpushClient {

	private static final String APPKEY ="32c409223f822935a64f5f1f";

	private static final String MASTERSECRET ="a0ace53beb7fdf06c93d39f3";

	private static JPushClient jpushClient = null;

    //保存离线的时长，最多支持10天     （Ps：不填写时，默认是保存一天的离线消息     0：代表不保存离线消息）
	private static int timeToLive = 60 * 60 * 24 ;

	private static Logger logger = Logger.getLogger(JpushClient.class);
    
	private static final String quoteSuccess ="报价成功提醒";
	
	private static final String orderPaySuccess="订单支付成功";
	
	private static final String everyAwardMoney="每日奖金收入";
	
	private static final String everyGoldBean="每日金豆";
	
	private static final String sendFirst="给上一级发信息";
	
	private static final String sendSecond="给上二级发信息";

	public static void saveAppMessage(String content,String messageType,String custId,String messageUrl,IAppRemindMessageService appRemindMessageService){
		
		
		AppRemindMessage appRemindMessage = new AppRemindMessage();
		appRemindMessage.setId(CommonUtils.getKeyId());
		appRemindMessage.setCustId(custId);
		appRemindMessage.setContent(content);
		appRemindMessage.setMessageUrl(messageUrl);
		appRemindMessage.setMessageStatus("unRead");
		appRemindMessage.setCreateTime(DateUtils.getCurrent());
		appRemindMessage.setMessageType(messageType);
		
		appRemindMessage.setModelStatus(ModelStatus.add);
		appRemindMessageService.applyChange(appRemindMessage);
	}
	
/**
 * ++++++++++++++++++++++++报价成功提醒
 */
public static PushPayload tomeasureApp(String insuName ,String carLicenseNo,String totalMoney,Customer customer,String id,IAppRemindMessageService appRemindMessageService) {
	
	String messageType="quoteSuccess";
	String custId=customer.getId();
	String content="您的报价订单已出炉,报价项目为"+insuName+",报价内容为"+carLicenseNo+",价格为"+totalMoney+",点击进入测算详情(只一次有效)";
	String messageUrl="";
	saveAppMessage(content,messageType,custId,messageUrl,appRemindMessageService);
	
        return PushPayload.newBuilder().setPlatform(Platform.android_ios())
                .setAudience(Audience.alias(String.valueOf(customer.getUserIdentity())))
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(AndroidNotification.newBuilder()
                                .addExtra("type", "quoteSuccess")
                                .addExtra("id", id)
                                .setAlert("您的报价订单已出炉,报价项目为"+insuName+",报价内容为"+carLicenseNo+",价格为"+totalMoney+",点击进入测算详情(只一次有效)")
                                .build())
                        .addPlatformNotification(IosNotification.newBuilder()
                                .addExtra("type", "quoteSuccess")
                                .setAlert("您的报价订单已出炉,报价项目为"+insuName+",报价内容为"+carLicenseNo+",价格为"+totalMoney+",点击进入测算详情(只一次有效)")
                                .build())
                        .build())
                .setOptions(Options.newBuilder()
                        .setApnsProduction(false)//true-推送生产环境 false-推送开发环境（测试使用参数）
                        .setTimeToLive(timeToLive)
                        .build())
                .build();
    }
public static void sendTomeasureApp(String insuName ,String carLicenseNo,String totalMoney,Customer customer,String id,IAppRemindMessageService appRemindMessageService){
    try {
        jpushClient = new JPushClient(MASTERSECRET, APPKEY, null, ClientConfig.getInstance());
        //生成推送的内容
        PushPayload payload = tomeasureApp(insuName, carLicenseNo, totalMoney, customer, id,appRemindMessageService);
        payload.resetOptionsTimeToLive(timeToLive);
        PushResult result = jpushClient.sendPush(payload);
        logger.info("Got result - " + result);
    } catch (APIConnectionException e) {
        // Connection error, should retry later
        logger.error("Connection error, should retry later", e);

    } catch (APIRequestException e) {
        // Should review the error, and fix the request
        logger.error("Should review the error, and fix the request", e);
        logger.info("HTTP Status: " + e.getStatus());
        logger.info("Error Code: " + e.getErrorCode());
        logger.info("Error Message: " + e.getErrorMessage());
    }
    
}
/**
 *++++++++++++++++++++++++++++++ 订单支付成功通知
 */
public static PushPayload orderPaySuccessApp(double totalFee, Customer customer,IAppRemindMessageService appRemindMessageService) {
	
	String messageType="orderPaySuccess";
	String custId=customer.getId();
	String content="恭喜您，订单支付成功，一共支付"+totalFee+"元";
	String messageUrl="";
	saveAppMessage(content,messageType,custId,messageUrl,appRemindMessageService);
	
	return PushPayload.newBuilder().setPlatform(Platform.android_ios())
            .setAudience(Audience.alias(String.valueOf(customer.getUserIdentity())))
            .setNotification(Notification.newBuilder()
                    .addPlatformNotification(AndroidNotification.newBuilder()
                            .addExtra("type", "orderPaySuccess")
                            .setAlert("恭喜您，订单支付成功，一共支付"+totalFee+"元")
                            .build())
                    .addPlatformNotification(IosNotification.newBuilder()
                            .addExtra("type", "orderPaySuccess")
                            .setAlert("恭喜您，订单支付成功，一共支付"+totalFee+"元")
                            .build())
                    .build())
            .setOptions(Options.newBuilder()
                    .setApnsProduction(false)//true-推送生产环境 false-推送开发环境（测试使用参数）
                    .setTimeToLive(timeToLive)
                    .build())
            .build();  
}
public static void sendorderPaySuccessApp(double totalFee, Customer customer,IAppRemindMessageService appRemindMessageService){
    try {
        jpushClient = new JPushClient(MASTERSECRET, APPKEY, null, ClientConfig.getInstance());
        //生成推送的内容
        PushPayload payload = orderPaySuccessApp(totalFee,customer,appRemindMessageService);
        payload.resetOptionsTimeToLive(timeToLive);
        PushResult result = jpushClient.sendPush(payload);
        logger.info("Got result - " + result);
    } catch (APIConnectionException e) {
        // Connection error, should retry later
        logger.error("Connection error, should retry later", e);

    } catch (APIRequestException e) {
        // Should review the error, and fix the request
        logger.error("Should review the error, and fix the request", e);
        logger.info("HTTP Status: " + e.getStatus());
        logger.info("Error Code: " + e.getErrorCode());
        logger.info("Error Message: " + e.getErrorMessage());
    }
}
/**
 * +++++++++++++++++++++++++  每日奖金收入提醒
 */
public static PushPayload awardMoneyApp(double money,Customer customer,IAppRemindMessageService appRemindMessageService) {
	
	String messageType="everyAwardMoney";
	String custId=customer.getId();
	String content="您今天的奖金收入为"+money+"元,点击进入奖金明细查看";
	String messageUrl="";
	saveAppMessage(content,messageType,custId,messageUrl,appRemindMessageService);
	
	return PushPayload.newBuilder().setPlatform(Platform.android_ios())
            .setAudience(Audience.alias(String.valueOf(customer.getUserIdentity())))
            .setNotification(Notification.newBuilder()
                    .addPlatformNotification(AndroidNotification.newBuilder()
                            .addExtra("type", "everyAwardMoney")
                            .setAlert("您今天的奖金收入为"+money+"元,点击进入奖金明细查看")
                            .build())
                    .addPlatformNotification(IosNotification.newBuilder()
                            .addExtra("type", "everyAwardMoney")
                            .setAlert("您今天的奖金收入为"+money+"元,点击进入奖金明细查看")
                            .build())
                    .build())
            .setOptions(Options.newBuilder()
                    .setApnsProduction(false)//true-推送生产环境 false-推送开发环境（测试使用参数）
                    .setTimeToLive(timeToLive)
                    .build())
            .build();  
}
public static void sendawardMoneyApp(double money,Customer customer,IAppRemindMessageService appRemindMessageService){
    try {
        jpushClient = new JPushClient(MASTERSECRET, APPKEY, null, ClientConfig.getInstance());
        //生成推送的内容
        PushPayload payload = awardMoneyApp(money,customer,appRemindMessageService);
        payload.resetOptionsTimeToLive(timeToLive);
        PushResult result = jpushClient.sendPush(payload);
        logger.info("Got result - " + result);
    } catch (APIConnectionException e) {
        // Connection error, should retry later
        logger.error("Connection error, should retry later", e);

    } catch (APIRequestException e) {
        // Should review the error, and fix the request
        logger.error("Should review the error, and fix the request", e);
        logger.info("HTTP Status: " + e.getStatus());
        logger.info("Error Code: " + e.getErrorCode());
        logger.info("Error Message: " + e.getErrorMessage());
    }
}
/**
 * +++++++++++++++++++++++++  每日金豆收入提醒
 */
public static PushPayload goldBeanApp(double goldBean,Customer customer,IAppRemindMessageService appRemindMessageService) {
	
	String messageType="everyGoldBean";
	String custId=customer.getId();
	String content="您今天的金豆收入为"+goldBean+"元,点击进入金豆明细查看";
	String messageUrl="";
	saveAppMessage(content,messageType,custId,messageUrl,appRemindMessageService);
	
	return PushPayload.newBuilder().setPlatform(Platform.android_ios())
            .setAudience(Audience.alias(String.valueOf(customer.getUserIdentity())))
            .setNotification(Notification.newBuilder()
                    .addPlatformNotification(AndroidNotification.newBuilder()
                            .addExtra("type", "everyGoldBean")
                            .setAlert("您今天的金豆收入为"+goldBean+"元,点击进入金豆明细查看")
                            .build())
                    .addPlatformNotification(IosNotification.newBuilder()
                            .addExtra("type", "everyGoldBean")
                            .setAlert("您今天的金豆收入为"+goldBean+"元,点击进入金豆明细查看")
                            .build())
                    .build())
            .setOptions(Options.newBuilder()
                    .setApnsProduction(false)//true-推送生产环境 false-推送开发环境（测试使用参数）
                    .setTimeToLive(timeToLive)
                    .build())
            .build();  
}
public static void sendgoldBeanApp(double goldBean,Customer customer,IAppRemindMessageService appRemindMessageService){
    try {
        jpushClient = new JPushClient(MASTERSECRET, APPKEY, null, ClientConfig.getInstance());
        //生成推送的内容
        PushPayload payload = goldBeanApp(goldBean,customer,appRemindMessageService);
        payload.resetOptionsTimeToLive(timeToLive);
        PushResult result = jpushClient.sendPush(payload);
        logger.info("Got result - " + result);
    } catch (APIConnectionException e) {
        // Connection error, should retry later
        logger.error("Connection error, should retry later", e);

    } catch (APIRequestException e) {
        // Should review the error, and fix the request
        logger.error("Should review the error, and fix the request", e);
        logger.info("HTTP Status: " + e.getStatus());
        logger.info("Error Code: " + e.getErrorCode());
        logger.info("Error Message: " + e.getErrorMessage());
    }
}
/**
 * 加入会员通知
 * currentCustomer是当前加入的人，firstCustomer是上一级，secondCustomer是上二级
 * 当传入参数firstCustomer和secondCustomer都不为空时，给上二级发信息
 * 当传入参数firstCustomer不为空，secondCustomer为空时，给上一级发信息
 */
public static PushPayload updateLevelApp(int userIdentity,Customer currentCustomer,Customer firstCustomer,Customer secondCustomer,String id,IAppRemindMessageService appRemindMessageService,String level) {
	String currentLevel=BaseEnumConstant.getGivenEnumByVlue(CustomerLevel.class,level );

	//给上一级发信息
	if(firstCustomer != null && secondCustomer == null){
		
		String custId=firstCustomer.getId();
		String messageType="sendFirst";
		String content="恭喜您，您推荐的"+currentCustomer.getUsername()+"成功加入"+currentLevel+",点击进入领取您的专属红包";
		String messageUrl="";
		saveAppMessage(content,messageType,custId,messageUrl,appRemindMessageService);
	
		return PushPayload.newBuilder().setPlatform(Platform.android_ios())
	            .setAudience(Audience.alias(String.valueOf(userIdentity)))
	            .setNotification(Notification.newBuilder()
	                    .addPlatformNotification(AndroidNotification.newBuilder()
	                            .addExtra("type", "sendFirst")
	                            .addExtra("id", id)
	                            .setAlert("恭喜您，您推荐的"+currentCustomer.getUsername()+"成功加入"+currentLevel+",点击进入领取您的专属红包")
	                            .build())
	                    .addPlatformNotification(IosNotification.newBuilder()
	                            .addExtra("type", "sendFirst")
	                            .addExtra("id", id)
	                            .setAlert("恭喜您，您推荐的"+currentCustomer.getUsername()+"成功加入"+currentLevel+",点击进入领取您的专属红包")
	                            .build())
	                    .build())
	            .setOptions(Options.newBuilder()
	                    .setApnsProduction(false)//true-推送生产环境 false-推送开发环境（测试使用参数）
	                    .setTimeToLive(timeToLive)
	                    .build())
	            .build();
		//给上二级发信息
	}else if(firstCustomer != null && secondCustomer != null){
		
		String firstLevel = BaseEnumConstant.getGivenEnumByVlue(CustomerLevel.class,firstCustomer.getLevel() );
		
		String custId=secondCustomer.getId();
		String messageType="sendSecond";
		String content="恭喜您，您的"+firstLevel+firstCustomer.getUsername()+",推荐的"+currentCustomer.getUsername()+"成功加入"+currentLevel+",点击进入我的团队查看";
		String messageUrl="";
		saveAppMessage(content,messageType,custId,messageUrl,appRemindMessageService);
		
		return PushPayload.newBuilder().setPlatform(Platform.android_ios())
	            .setAudience(Audience.alias(String.valueOf(userIdentity)))
	            .setNotification(Notification.newBuilder()
	                    .addPlatformNotification(AndroidNotification.newBuilder()
	                            .addExtra("type", "sendSecond")
	                            .setAlert("恭喜您，您的"+firstLevel+firstCustomer.getUsername()+",推荐的"+currentCustomer.getUsername()+"成功加入"+currentLevel+",点击进入我的团队查看")
	                            .build())
	                    .addPlatformNotification(IosNotification.newBuilder()
	                            .addExtra("type", "sendSecond")
	                            .setAlert("恭喜您，您的"+firstLevel+firstCustomer.getUsername()+",推荐的"+currentCustomer.getUsername()+"成功加入"+currentLevel+",点击进入我的团队查看")
	                            .build())
	                    .build())
	            .setOptions(Options.newBuilder()
	                    .setApnsProduction(false)//true-推送生产环境 false-推送开发环境（测试使用参数）
	                    .setTimeToLive(timeToLive)
	                    .build())
	            .build();
	}
	
	return null;
  }
public static void sendUpdateLevelApp(int userIdentity,Customer currentCustomer,Customer firstCustomer,Customer secondCustomer,String id,IAppRemindMessageService appRemindMessageService,String level){
    try {
        jpushClient = new JPushClient(MASTERSECRET, APPKEY, null, ClientConfig.getInstance());
        //生成推送的内容
        PushPayload payload = updateLevelApp(userIdentity,currentCustomer,firstCustomer,secondCustomer,id,appRemindMessageService,level);
        payload.resetOptionsTimeToLive(timeToLive);
        PushResult result = jpushClient.sendPush(payload);
        logger.info("Got result - " + result);
    } catch (APIConnectionException e) {
        // Connection error, should retry later
        logger.error("Connection error, should retry later", e);

    } catch (APIRequestException e) {
        // Should review the error, and fix the request
        logger.error("Should review the error, and fix the request", e);
        logger.info("HTTP Status: " + e.getStatus());
        logger.info("Error Code: " + e.getErrorCode());
        logger.info("Error Message: " + e.getErrorMessage());
    }
}

}
